package org.example.springboot.dao.impl;

import org.example.springboot.dao.UserDAO;
import org.example.springboot.entity.User;
import org.example.springboot.util.JDBCUtils;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 用户数据接口实现类
 */
@Repository
public class UserDAOImpl implements UserDAO {

    @Override
    public User selectByUsername(String username) {
        List<User> users = JDBCUtils.executeQuery(User.class,"select * from s_user where user_name like ?",username);
        if(users.isEmpty()){
            return null;
        }
        return users.get(0);
    }

    @Override
    public List<User> selectAll() {
        List<User> users = JDBCUtils.executeQuery(User.class,"select * from s_user");
        return users;
    }

    @Override
    public User selectById(String userId) {
        List<User> users = JDBCUtils.executeQuery(User.class,"select * from s_user where user_id = ?",userId);
        if(users.isEmpty()){
            return null;
        }
        return users.get(0);
    }

    @Override
    public boolean insert(User user) {
        int rows = JDBCUtils.executeUpdate("insert into s_user(user_id,user_name,user_pwd,user_type) values(?,?,?,?)",
                user.getUser_id(),user.getUser_name(),user.getUser_pwd(),user.getUser_type());
        return rows > 0;
    }

    @Override
    public boolean delete(String userId) {
        int rows = JDBCUtils.executeUpdate("delete from  s_user where user_id = ?",userId);
        return rows > 0;
    }

    @Override
    public boolean update(User user) {
        int rows = JDBCUtils.executeUpdate("update s_user set user_name=?,user_pwd=?,user_type=? where user_id =?",
                user.getUser_name(),user.getUser_pwd(),user.getUser_type(),user.getUser_id());
        return rows > 0;
    }

    @Override
    public Integer selectUserCount() {
        return JDBCUtils.executeCount("select count(*) from s_user");
    }

    @Override
    public List<User> selectUserLimits(int start, int row) {
        return JDBCUtils.executeQuery(User.class,"select * from s_user limit ?,?", start,row);
    }
}
